package com.um.swing.component;

import com.um.swing.bean.ImageItem;
import com.um.swing.common.inc.Constant;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class FileListCellRenderer extends JLabel implements ListCellRenderer {
    private static final Color selectBgColor = new Color(17, 103, 209);
    private static final Color selectTextColor = new Color(247, 248, 252);

    private static final Color textColor = new Color(181, 181, 181);
    private static final Color bgColor = new Color(0, 0, 0, 0);

    private int index = 0;//当前索引
    private ImageItem item;//当前数据引用


    public FileListCellRenderer() {
        setOpaque(true);
        setBorder(new EmptyBorder(0, 10, 0, 0));
    }

    @Override
    public void repaint(Rectangle r) {
        super.repaint(r);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Constant.COLOR_GREEN);
        g2d.setStroke(new BasicStroke(2));
        g2d.translate(0, this.getHeight() / 2);
        boolean isTowItem = index % 2 == 0;
        int y = 0;
        int left = 5;
        int offset = 5;
        int bHeight = this.getHeight() / 2;
        if (item.isTowPage()) {
            y = isTowItem ? offset : -offset;
            int y2 = isTowItem ? -offset : offset;
//            g2d.setColor(Color.RED);

            g2d.drawLine(7, y2, left, y2);
            g2d.drawLine(left, y2, left, isTowItem ? -bHeight : bHeight);
        }
//        g2d.setColor(Color.GREEN);
        g2d.drawLine(7, y, left, y);
        g2d.drawLine(left, y, left, isTowItem ? bHeight : -bHeight);

    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        this.item = (ImageItem) value;
        this.index = index;
        this.setText(item.getName());
        int width = this.getFontMetrics(this.getFont()).stringWidth(item.getName());
        this.setPreferredSize(new Dimension(width + 20, 27));

        if (isSelected) {
            setBackground(selectBgColor);
            setForeground(selectTextColor);
        } else {
            setBackground(bgColor);
            setForeground(textColor);
        }

        if (item.isOverPoint()) {
            setForeground(Constant.COLOR_GREEN);
        }

        this.repaint();
        return this;
    }
}
